package com.cdvtc.news.web;

import com.cdvtc.news.entity.User;
import com.cdvtc.news.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

//import javax.jws.WebParam;
//import java.text.DateFormat;
//import java.text.SimpleDateFormat;

@Controller
public class SignupController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/signup", method = RequestMethod.GET)
    public String index(){
        return "signup";
    }

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    public String signup(@ModelAttribute User user, Model model) {
        /**
         * 数据验证
         */
        String error_account = null;
        if(userService.isUserExisted("account", user.getAccount())){
            error_account = "账户已经存在！";
            model.addAttribute("error_account", error_account);
        }
        String error_nickname = null;
        if(userService.isUserExisted("nickname", user.getNickname())){
            error_nickname = "昵称已经存在！";
            model.addAttribute("error_nickname", error_nickname);
        }
        String error_mobile = null;
        if(userService.isUserExisted("mobile", user.getMobile())){
            error_mobile = "手机号码已经存在！";
            model.addAttribute("error_mobile", error_mobile);
        }
        String error_email = null;
        if(user.getEmail() != null && userService.isUserExisted("email", user.getEmail())){ // 注意：email可能为null
            error_email = "电子邮件已经存在！";
            model.addAttribute("error_email", error_email);
        }

        /**
         * 根据验证结果进行页面跳转
         */
        if(error_account==null && error_nickname==null && error_mobile==null && error_email==null) { //验证通过
            userService.addUser(user);
            return "redirect:/login"; //进入登陆页面
        }else { //返回至注册页面
            return "/signup";
        }

    }
}
